<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');

if ( ! function_exists('utf8substr'))
{
	function utf8substr($str, $from, $len)
	{
	    return preg_replace('#^(?:[\x00-\x7F]|[\xC0-\xFF][\x80-\xBF]+){0,'.$from.'}'.
	                       '((?:[\x00-\x7F]|[\xC0-\xFF][\x80-\xBF]+){0,'.$len.'}).*#s',
	                       '$1',$str);
	}
}
if ( ! function_exists('filterimg'))
{
	function filterimg($string)
	{
	 
	 $content=preg_replace('/<img.*?(?: |\\t|\\r|\\n)?src=[\'"]?(.+?)[\'"]?(?:(?: |\\t|\\r|\\n)+.*?)?>/sim', '', $string);
	 return $content;
	}
}
if ( ! function_exists('strdisplay'))
{
	function strdisplay($str, $length = 1)
	{
		$xing = "";
		for($i = 0; $i < $length; $i++){
			$xing .= '*';
		}
		if($str == null || $str == ''){
			return '';
		}
		if($length >= strlen($str)){
			return $str;
		}
		if( preg_match("/^[\x80-\xffa-zA-Z0-9]{3,60}$/", $str) ){
			$len = mb_strlen($str);
			return mb_substr($str, 0, $len-$length, 'utf-8').$xing;	
		}else{
			$len = strlen($str);
			return substr($str, 0, $len-$length).$xing;	
		}
	}
}

if ( ! function_exists('strdisplay_start'))
{
	function strdisplay_start($str, $length = 1)
	{
		$xing = "**";
		if($str == null || $str == ''){
			return '';
		}
		if(!preg_match("/[^\x80-\xff]/",$str)){
			return mb_substr($str, 0, 1, 'utf-8').$xing;	
		}else{
			$len = strlen($str)/2;
			return substr_replace($str,str_repeat($xing,$len),ceil(($len)/2),$len);	
		}
	}
}


if ( ! function_exists('strdisplay_title'))
{
	function strdisplay_title($str, $length = 1)
	{
		if(!preg_match("/[^\x80-\xff]/",$str)){
			return mb_substr($str, 0, $length, 'utf-8');	
		}else{
			return substr($str, 0, $length);	
		}
	}
}

if ( ! function_exists('rand_string'))
{
	function rand_string($ukey="",$len=6,$type='1',$utype='1',$addChars='') {
	    $str ='';
	    switch($type) {
	        case 0:
	            $chars='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.$addChars;
	            break;
	        case 1:
	            $chars= str_repeat('0123456789',3);
	            break;
	        case 2:
	            $chars='ABCDEFGHIJKLMNOPQRSTUVWXYZ'.$addChars;
	            break;
	        case 3:
	            $chars='abcdefghijklmnopqrstuvwxyz123456789'.$addChars;
	            break;
	        default :
	            $chars='ABCDEFGHIJKMNPQRSTUVWXYZabcdefghijkmnpqrstuvwxyz23456789'.$addChars;
	            break;
	    }
	    if($len>10 ) {
	        $chars= $type==1? str_repeat($chars,$len) : str_repeat($chars,5);
	    }
	    $chars   =   str_shuffle($chars);
	    $str     =   substr($chars,0,$len);
	    return $str;
	}
}

if( ! function_exists('getSignature')){
	function getSignature($MerNo, $BillNo, $Amount, $ReturnURL, $MD5key){
		$_SESSION['MerNo'] = $MerNo;
	 	$_SESSION['MD5key'] = $MD5key;
		$sign_params  = array(
	        'MerNo'       => $MerNo,
	        'BillNo'       => $BillNo, 
	        'Amount'         => $Amount,   
	        'ReturnURL'       => $ReturnURL
	    );
	  	$sign_str = "";
	  	ksort($sign_params);
	  	foreach ($sign_params as $key => $val) {
	       $sign_str .= sprintf("%s=%s&", $key, $val);                
	    }
	   return strtoupper(md5($sign_str. strtoupper(md5($MD5key))));   
	}
}

if( ! function_exists('getSignatureCallback')){
 function getSignatureCallback($MerNo, $BillNo, $Amount, $Succeed, $MD5key){
			$sign_params  = array(
        	'MerNo'         => $MerNo,
        	'BillNo'        => $BillNo, 
        	'Amount'        => $Amount,   
        	'Succeed'       => $Succeed
    			);
    
			$sign_str = "";
			ksort($sign_params);
			foreach ($sign_params as $key => $val) {              
                
                $sign_str .= sprintf("%s=%s&", $key, $val);
                               
            }
           //print $sign_str;print '<br/><br/><br/>';
  		return strtoupper(md5($sign_str. strtoupper(md5($MD5key))));   


	}  
}	

if( ! function_exists('cut_str')){
	function cut_str($sourcestr,$cutlength){
		$returnstr='';
		$i=0;
		$n=0;
		$str_length=strlen($sourcestr);//字符串的字节数
		while (($n<$cutlength) and ($i<=$str_length))
		{
			$temp_str=substr($sourcestr,$i,1);
			$ascnum=Ord($temp_str);//得到字符串中第$i位字符的ascii码
			if ($ascnum>=224) //如果ASCII位高与224，
			{
				$returnstr=$returnstr.substr($sourcestr,$i,3); //根据UTF-8编码规范，将3个连续的字符计为单个字符
				$i=$i+3; //实际Byte计为3
				$n++; //字串长度计1
			}
			elseif ($ascnum>=192) //如果ASCII位高与192，
			{
				$returnstr=$returnstr.substr($sourcestr,$i,2); //根据UTF-8编码规范，将2个连续的字符计为单个字符
				$i=$i+2; //实际Byte计为2
				$n++; //字串长度计1
			}
			elseif ($ascnum>=65 && $ascnum<=90) //如果是大写字母，
			{
				$returnstr=$returnstr.substr($sourcestr,$i,1);
				$i=$i+1; //实际的Byte数仍计1个
				$n++; //但考虑整体美观，大写字母计成一个高位字符
			}
			else //其他情况下，包括小写字母和半角标点符号，
			{
				$returnstr=$returnstr.substr($sourcestr,$i,1);
				$i=$i+1; //实际的Byte数计1个
				$n=$n+0.5; //小写字母和半角标点等与半个高位字符宽...
			}
		}
		if ($str_length>$cutlength){
			$returnstr = $returnstr."...";//超过长度时在尾处加上省略号
		}
		
		return $returnstr;
	}
}

if( ! function_exists('filePath')){
	function filePath($filename,$data="",$path=""){
		$path = APPPATH.$path;
		if($data==""){
			$f = explode("/",$filename);
			$num = count($f);
			if($num>2){
				$fx = $f;
				array_pop($f);
				$pathe = implode("/",$f);
				$re = F($fx[$num-1],'',$pathe."/");
			}else{
				isset($f[1])?$re = F($f[1],'',APPPATH.$f[0]."/"):$re = F($f[0]);
			}
			return $re;
		}else{
			
			if(!empty($path)) $re = F($filename,$data,$path);
			else $re = F($filename,$data);
		}
	}
}

/**
 * 快速文件数据读取和保存 针对简单类型数据 字符串、数组
 * @param string $name 缓存名称
 * @param mixed $value 缓存值
 * @param string $path 缓存路径
 * @return mixed
 */
if( ! function_exists('F')){
	function F($name, $value='', $path=DATA_PATH) {
	    static $_cache  = array();
	    $filename       = $path . $name . '.php';
	 
	    if ('' !== $value) {
	    	
	        if (is_null($value)) {
	        	
	            // 删除缓存
	            return false !== strpos($name,'*')?array_map("unlink", glob($filename)):unlink($filename);
	        } else {
	            // 缓存数据
	            $dir            =   dirname($filename);
	            // 目录不存在则创建
	            if (!is_dir($dir))
	                mkdir($dir,0755,true);
	            $_cache[$name]  =   $value;
	            return file_put_contents($filename, strip_whitespace("<?php\treturn " . var_export($value, true) . ";?>"));
	        }
	    }
	    
	    
	     
	    if (isset($_cache[$name]))
	        return $_cache[$name];
	    // 获取缓存数据
	    if (is_file($filename)) {
	        $value          =   include $filename;
	        $_cache[$name]  =   $value;
	    } else {
	        $value          =   false;
	    }
	    
	    return $value;
	}
}

if( ! function_exists('de_xie')){
	function de_xie($arr){
		$data=array();
		if(is_array($arr)){
			foreach($arr as $key=>$v){
				if(is_array($v)){
					foreach($v as $skey=>$sv){
						if(is_array($sv)){
								
						}else{
							$v[$skey] = stripslashes($sv);
						}
					}
					$data[$key] = $v;
				}else{
					$data[$key] = stripslashes($v);
				}
			}
		}else{
			$data = stripslashes($arr);
		}
		return $data;
	}
}

if( ! function_exists('getMonthLastDay')){
	function getMonthLastDay($month) {
		$year = date('Y');
	    switch ($month) {
	        case 4 :
	        case 6 :
	        case 9 :
	        case 11 :
	            $days = 30;
	            break;
	        case 2 :
	            if ($year % 4 == 0) {
	                if ($year % 100 == 0) {
	                    $days = $year % 400 == 0 ? 29 : 28;
	                } else {
	                    $days = 29;
	                }
	            } else {
	                $days = 28;
	            }
	            break;
	
	        default :
	            $days = 31;
	            break;
	    }
	    
	    return $days;
	}
}

/** 
 * 数组分页函数  核心函数  array_slice 
 * 用此函数之前要先将数据库里面的所有数据按一定的顺序查询出来存入数组中 
 * $count   每页多少条数据 
 * $page   当前第几页 
 * $array   查询出来的所有数组 
 * order 0 - 不变     1- 反序 
 */  
if( ! function_exists('page_array')){
	function page_array($count,$page,$array,$order){  
	    global $countpage; #定全局变量  
	    $page=(empty($page))?'1':$page; #判断当前页面是否为空 如果为空就表示为第一页面   
	       $start=($page-1)*$count; #计算每次分页的开始位置  
	    if($order==1){  
	      $array=array_reverse($array);  
	    }     
	    $totals=count($array);    
	    $countpage=ceil($totals/$count); #计算总页面数  
	    $pagedata=array();  
	    $pagedata=array_slice($array,$start,$count);  
	    
	    return $pagedata;  #返回查询数据  
	}  
}


/** 
 * 分页及显示函数 
 * $countpage 全局变量，照写 
 * $url 当前url 
 */
if( ! function_exists('show_array')){  
	function show_array($countpage,$url){  
	     $page=empty($_GET['page'])?1:$_GET['page'];  
	     if($page > 1){  
	        $uppage=$page-1;  
	  
	     }else{  
	        $uppage=1;  
	     }  
	  
	     if($page < $countpage){  
	        $nextpage=$page+1;  
	  
	     }else{  
	            $nextpage=$countpage;  
	     }  
	         
	        $str='<div style="border:1px; width:300px; height:30px; color:#9999CC">';  
	    $str.="<span>共  {$countpage}  页 / 第 {$page} 页</span>";  
	    $str.="<span><a href='$url?page=1'>   首页  </a></span>";  
	    $str.="<span><a href='$url?page={$uppage}'> 上一页  </a></span>";  
	    $str.="<span><a href='$url?page={$nextpage}'>下一页  </a></span>";  
	    $str.="<span><a href='$url?page={$countpage}'>尾页  </a></span>";  
	    $str.='</div>';  
	    return $str;  
	} 
} 


if ( ! function_exists('paginate_three') )
{
	function paginate_three($url, $page, $tpages, $adjacents, $pattern='/\{p\}/') {
	
		$prevlabel = "&lsaquo; 前一页";
		$nextlabel = "后一页 &rsaquo;";
		
		$out = "";
		
		$_url = array();
		if($pattern){
			$_url = preg_split($pattern, $url);
		}else{
			$_url = $url;
		}
		if(!isset($_url[1])){
			$_url[1] = '';
		}
		
		// previous
		if($page==1) {
			//$out.= "<span>" . $prevlabel . "</span>\n";
		}
		elseif($page==2) {
			$out.= "<a href=\"" . $_url[0].'1'.$_url[1] . "\">" . $prevlabel . "</a>\n";
		}
		else {
			$out.= "<a href=\"" . $_url[0].($page-1).$_url[1] . "\">" . $prevlabel . "</a>\n";
		}
	
		// first
		if($page>($adjacents+1)) {
			$out.= "<a href=\"" . $_url[0].'1'.$_url[1] . "\">1</a>\n";
		}
	
		// interval
		if($page>($adjacents+2)) {
			$out.= "...\n";
		}
	
		// pages
		$pmin = ($page>$adjacents) ? ($page-$adjacents) : 1;
		$pmax = ($page<($tpages-$adjacents)) ? ($page+$adjacents) : $tpages;
		for($i=$pmin; $i<=$pmax; $i++) {
			if($i==$page) {
				
				$out.= "<strong>" . $i . "</strong>\n";
				
			}
			elseif($i==1) {
				$out.= "<a href=\"" . $_url[0].'1'.$_url[1] . "\">" . $i . "</a>\n";
			}
			else {
				$out.= "<a href=\"" . $_url[0].$i.$_url[1] . "\">" . $i . "</a>\n";
			}
		}
	
		// interval
		if($page<($tpages-$adjacents-1)) {
			$out.= "...\n";
		}
	
		// last
		if($page<($tpages-$adjacents)) {
			$out.= "<a href=\"" . $_url[0].$tpages.$_url[1] . "\">" . $tpages . "</a>\n";
		}
	
		// next
		if($page<$tpages) {
			$out.= "<a href=\"" . $_url[0].($page+1).$_url[1] . "\">" . $nextlabel . "</a>\n";
		}
		else {
			$out.= "<span>" . $nextlabel . "</span>\n";
		}
	
	
		return $out;
	}
	
	// ***** by liub 20150101 生成随机数字(可修正为随机字符串)
	if ( ! function_exists('create_num') ){	
		 function create_num( $length = 6 ) {  
			$chars = '5102849673';  
			$num = "";  
			for ( $i = 0; $i < $length; $i++ )  {  
				$num .= $chars[ mt_rand(0, strlen($chars) - 1) ];  
			}  
			return $num;  
		} 
	}
}
